import React from 'react'
import _ from 'underscore'
import $ from 'jquery'
import View from 'lib/View.jsx'
import dispatcher from 'lib/dispatcher'
import Layout from '../common/layout.jsx'
import Card from 'lib/components/card.jsx'
import GridWidget from 'lib/components/GridWidget.jsx'
import Scope from './MainScope.es6'
import RuleForm from './RuleForm.jsx'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import {Confirm} from 'lib/components/Confirm.jsx'
import {remove} from '../apis/urlGroup'
function newRule(domains){
  RuleForm.mount({
    domains:domains
  })
}

export default class MainView extends View {
  constructor(props){
    super(props);
    this.cols = [{
      title:'名称',
      key:'name'
    },{
      title:'匹配模式',
      key:'pattern'
    },{
      title:'是否生效',
      key:'enable',
      formatter:function(v){return v?'是':'否'}
    },{
      title:'是否忽略',
      key:'hidden',
      formatter:function(v){return v?'是':'否'}
    },{
      width: 70,
      render:function(fmtVal,rowData,rowIndex,colIndex){
        function showRuleForm(){
          RuleForm.mount({
            domains:this.state.domains,
            urlGroup:rowData
          })
        }
        var del = _.once(function delApp(){
          Confirm(<p>确定要删除吗？</p>).then(function(){
            remove({
              id:rowData.id
            }).post().then((res) => {
              if(res.result){
                Success('删除成功！')
              }else{
                Warning('删除失败！')
              }
            },() => {
              Warning('删除失败！')
            })
            dispatcher.dispatch({
              $type:'delete_urlgroup',
              id:rowData.id
            })
          })
        })
        return (
          <div className="operation">
            <a className="iconfont" onClick={showRuleForm} href="javascript:;">&#xe61e;</a>
            <a className="iconfont" onClick={del} href="javascript:;">&#xe61f;</a>
          </div>
        )
      }
    }]
  }
  render(){
    return (
      <Layout title="网络" subtitle="自定义url归类" hideTime={true} hideVersion={true}>
        <div className="box">
          <Card title="URL匹配规则" extra={
            this.state.domains.length?(
              <a href="javascript:;" className="btn-green" onClick={newRule.bind(null,this.state.domains)}>添加</a>
            ):null
          }>
            <GridWidget cols={this.cols} store={this.state.grid}/>
          </Card>
        </div>
      </Layout>
    )
  }
}
MainView.defaultProps = {
  Scope:Scope
}
